/**
 * 实时通知消息处理服务
 */
import { useNotificationsStore } from '../store/notifications.js'

class NotificationMessageHandler {
  constructor() {
    this.notificationsStore = null
    this.messageQueue = []
    this.isProcessing = false
    this.isInitialized = false
    this.wsService = null // 缓存wsService实例
    this.retryCount = 0
    
    // 绑定方法
    this.handleMessage = this.handleMessage.bind(this)
    this.processMessageQueue = this.processMessageQueue.bind(this)
    this.markAsRead = this.markAsRead.bind(this)
    this.syncReadStatus = this.syncReadStatus.bind(this)
    
    // 延迟初始化，避免在模块加载时立即执行
    setTimeout(() => {
      this.initialize()
    }, 2000) // 增加延迟时间到2秒
  }

  /**
   * 获取WebSocket服务实例
   */
  async getWsService() {
    if (!this.wsService) {
      try {
        // 尝试多次导入，确保模块完全加载
        let attempts = 0
        let wsService = null
        
        while (attempts < 3 && !wsService) {
          try {
            const module = await import('./websocket.js')
            wsService = module.default
            
            // 验证wsService是否有效
            if (wsService && typeof wsService.on === 'function') {
              break
            } else {
              console.warn(`⚠️ WebSocket服务无效，尝试第${attempts + 1}次...`)
              wsService = null
            }
          } catch (importError) {
            console.warn(`⚠️ 导入WebSocket服务失败，尝试第${attempts + 1}次:`, importError)
          }
          
          attempts++
          if (attempts < 3) {
            await new Promise(resolve => setTimeout(resolve, 200))
          }
        }
        
        if (!wsService) {
          console.error('❌ 无法加载WebSocket服务')
          return null
        }
        
        this.wsService = wsService
        console.log('✅ WebSocket服务加载成功')
      } catch (error) {
        console.error('❌ 获取WebSocket服务失败:', error)
        return null
      }
    }
    return this.wsService
  }

  /**
   * 初始化消息处理器
   */
  async initialize() {
    // 防止重复初始化
    if (this.isInitialized) {
      console.log('📨 消息处理器已初始化，跳过')
      return
    }

    try {
      console.log('🔄 开始初始化消息处理器...')
      
      // 获取wsService实例
      const wsService = await this.getWsService()
      
      // 检查wsService是否可用
      if (!wsService) {
        console.warn('⚠️ WebSocket服务不可用，延迟重试')
        setTimeout(() => this.initialize(), 1000)
        return
      }

      console.log('✅ WebSocket服务验证通过，注册事件监听器...')

      // 注册WebSocket事件监听器
      wsService.on('connected', this.onConnected.bind(this))
      wsService.on('disconnected', this.onDisconnected.bind(this))
      wsService.on('message', this.handleMessage)
      wsService.on('notification', this.handleNotification.bind(this))
      wsService.on('ticket_update', this.handleTicketUpdate.bind(this))
      wsService.on('user_online', this.handleUserOnline.bind(this))
      wsService.on('system_message', this.handleSystemMessage.bind(this))
      wsService.on('notification_click', this.handleNotificationClick.bind(this))
      
      this.isInitialized = true
      console.log('📨 消息处理器初始化完成')
    } catch (error) {
      console.error('❌ 消息处理器初始化失败:', error)
      this.isInitialized = false
      // 延迟重试，但限制重试次数
      if (this.retryCount === undefined) {
        this.retryCount = 0
      }
      if (this.retryCount < 5) {
        this.retryCount++
        console.log(`🔄 第${this.retryCount}次重试初始化...`)
        setTimeout(() => this.initialize(), 2000)
      } else {
        console.error('❌ 消息处理器初始化失败次数过多，停止重试')
      }
    }
  }

  /**
   * WebSocket连接成功
   */
  onConnected() {
    console.log('✅ WebSocket连接成功，开始处理消息队列')
    this.processMessageQueue()
  }

  /**
   * WebSocket断开连接
   */
  onDisconnected() {
    console.log('🔌 WebSocket断开连接，暂停消息处理')
    this.isProcessing = false
  }

  /**
   * 处理接收到的消息
   */
  handleMessage(data) {
    console.log('📨 处理消息:', data)
    
    // 将消息加入队列
    this.messageQueue.push({
      ...data,
      timestamp: Date.now(),
      id: data.id || `msg_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
    })
    
    // 如果WebSocket已连接，立即处理
    this.getWsService().then(wsService => {
      if (wsService && wsService.isConnected()) {
        this.processMessageQueue()
      }
    })
  }

  /**
   * 处理消息队列
   */
  async processMessageQueue() {
    if (this.isProcessing || this.messageQueue.length === 0) {
      return
    }

    this.isProcessing = true
    
    try {
      while (this.messageQueue.length > 0) {
        const message = this.messageQueue.shift()
        await this.processMessage(message)
      }
    } catch (error) {
      console.error('❌ 处理消息队列失败:', error)
    } finally {
      this.isProcessing = false
    }
  }

  /**
   * 处理单个消息
   */
  async processMessage(message) {
    const { type, payload } = message
    
    try {
      switch (type) {
        case 'notification':
          await this.handleNotificationMessage(payload)
          break
        case 'ticket_update':
          await this.handleTicketUpdateMessage(payload)
          break
        case 'user_online':
          await this.handleUserOnlineMessage(payload)
          break
        case 'system_message':
          await this.handleSystemMessage(payload)
          break
        case 'read_status_update':
          await this.handleReadStatusUpdate(payload)
          break
        default:
          console.log('📨 未知消息类型:', type)
      }
    } catch (error) {
      console.error(`❌ 处理消息失败 (${type}):`, error)
    }
  }

  /**
   * 处理通知消息
   */
  async handleNotificationMessage(payload) {
    console.log('🔔 处理通知消息:', payload)
    
    // 获取通知store
    if (!this.notificationsStore) {
      this.notificationsStore = useNotificationsStore()
    }
    
    // 添加到通知列表
    const notification = {
      id: payload.id || `notif_${Date.now()}`,
      title: payload.title || '新通知',
      content: payload.content || payload.message,
      type: payload.type || 'info',
      priority: payload.priority || 'normal',
      category: payload.category || 'general',
      sender: payload.sender,
      timestamp: payload.timestamp || Date.now(),
      isRead: false,
      data: payload.data || {}
    }
    
    // 添加到store
    this.notificationsStore.addNotification(notification)
    
    // 更新未读计数
    this.notificationsStore.updateUnreadCount()
    
    // 显示桌面通知
    this.showDesktopNotification(notification)
    
    // 播放提示音
    this.playNotificationSound(payload.priority)
  }

  /**
   * 处理工单更新消息
   */
  async handleTicketUpdateMessage(payload) {
    console.log('🎫 处理工单更新消息:', payload)
    
    const { ticketId, action, data } = payload
    
    // 根据不同的更新类型处理
    switch (action) {
      case 'created':
        await this.handleTicketCreated(ticketId, data)
        break
      case 'updated':
        await this.handleTicketUpdated(ticketId, data)
        break
      case 'assigned':
        await this.handleTicketAssigned(ticketId, data)
        break
      case 'status_changed':
        await this.handleTicketStatusChanged(ticketId, data)
        break
      case 'commented':
        await this.handleTicketCommented(ticketId, data)
        break
      default:
        console.log('🎫 未知工单更新类型:', action)
    }
  }

  /**
   * 处理用户上线消息
   */
  async handleUserOnlineMessage(payload) {
    console.log('👤 处理用户上线消息:', payload)
    
    const { userId, username, timestamp } = payload
    
    // 创建用户上线通知
    const notification = {
      id: `user_online_${userId}_${timestamp}`,
      title: '用户上线',
      content: `${username} 已上线`,
      type: 'info',
      priority: 'low',
      category: 'user',
      sender: { id: userId, username },
      timestamp: timestamp,
      isRead: false,
      data: payload
    }
    
    if (this.notificationsStore) {
      this.notificationsStore.addNotification(notification)
    }
  }

  /**
   * 处理系统消息
   */
  async handleSystemMessage(payload) {
    console.log('⚙️ 处理系统消息:', payload)
    
    const { level, message, data } = payload
    
    // 根据系统消息级别处理
    switch (level) {
      case 'error':
        console.error('🚨 系统错误:', message)
        break
      case 'warning':
        console.warn('⚠️ 系统警告:', message)
        break
      case 'info':
        console.log('ℹ️ 系统信息:', message)
        break
      default:
        console.log('📢 系统消息:', message)
    }
    
    // 创建系统通知
    const notification = {
      id: `system_${Date.now()}`,
      title: '系统消息',
      content: message,
      type: level,
      priority: level === 'error' ? 'high' : 'normal',
      category: 'system',
      timestamp: Date.now(),
      isRead: false,
      data: data
    }
    
    if (this.notificationsStore) {
      this.notificationsStore.addNotification(notification)
    }
  }

  /**
   * 处理已读状态更新
   */
  async handleReadStatusUpdate(payload) {
    console.log('📖 处理已读状态更新:', payload)
    
    const { notificationId, isRead, userId } = payload
    
    if (this.notificationsStore) {
      this.notificationsStore.updateNotificationReadStatus(notificationId, isRead)
    }
  }

  /**
   * 处理工单创建
   */
  async handleTicketCreated(ticketId, data) {
    const notification = {
      id: `ticket_created_${ticketId}`,
      title: '新工单创建',
      content: `工单 #${ticketId} 已创建`,
      type: 'success',
      priority: 'normal',
      category: 'ticket',
      timestamp: Date.now(),
      isRead: false,
      data: { ticketId, ...data }
    }
    
    if (this.notificationsStore) {
      this.notificationsStore.addNotification(notification)
    }
  }

  /**
   * 处理工单更新
   */
  async handleTicketUpdated(ticketId, data) {
    const notification = {
      id: `ticket_updated_${ticketId}`,
      title: '工单更新',
      content: `工单 #${ticketId} 已更新`,
      type: 'info',
      priority: 'normal',
      category: 'ticket',
      timestamp: Date.now(),
      isRead: false,
      data: { ticketId, ...data }
    }
    
    if (this.notificationsStore) {
      this.notificationsStore.addNotification(notification)
    }
  }

  /**
   * 处理工单分配
   */
  async handleTicketAssigned(ticketId, data) {
    const notification = {
      id: `ticket_assigned_${ticketId}`,
      title: '工单分配',
      content: `工单 #${ticketId} 已分配给 ${data.assignee}`,
      type: 'info',
      priority: 'high',
      category: 'ticket',
      timestamp: Date.now(),
      isRead: false,
      data: { ticketId, ...data }
    }
    
    if (this.notificationsStore) {
      this.notificationsStore.addNotification(notification)
    }
  }

  /**
   * 处理工单状态变更
   */
  async handleTicketStatusChanged(ticketId, data) {
    const notification = {
      id: `ticket_status_${ticketId}`,
      title: '工单状态变更',
      content: `工单 #${ticketId} 状态变更为 ${data.status}`,
      type: 'info',
      priority: 'normal',
      category: 'ticket',
      timestamp: Date.now(),
      isRead: false,
      data: { ticketId, ...data }
    }
    
    if (this.notificationsStore) {
      this.notificationsStore.addNotification(notification)
    }
  }

  /**
   * 处理工单评论
   */
  async handleTicketCommented(ticketId, data) {
    const notification = {
      id: `ticket_comment_${ticketId}`,
      title: '工单评论',
      content: `工单 #${ticketId} 有新评论`,
      type: 'info',
      priority: 'normal',
      category: 'ticket',
      timestamp: Date.now(),
      isRead: false,
      data: { ticketId, ...data }
    }
    
    if (this.notificationsStore) {
      this.notificationsStore.addNotification(notification)
    }
  }

  /**
   * 显示桌面通知
   */
  showDesktopNotification(notification) {
    if (!('Notification' in window)) {
      console.warn('⚠️ 浏览器不支持桌面通知')
      return
    }

    if (Notification.permission === 'granted') {
      const desktopNotification = new Notification(notification.title, {
        body: notification.content,
        icon: '/favicon.ico',
        tag: notification.id,
        data: notification
      })

      desktopNotification.onclick = () => {
        window.focus()
        desktopNotification.close()
        
        // 标记为已读
        this.markAsRead(notification.id)
        
        // 触发通知点击事件
        this.triggerNotificationClick(notification)
      }
    } else if (Notification.permission !== 'denied') {
      Notification.requestPermission().then(permission => {
        if (permission === 'granted') {
          this.showDesktopNotification(notification)
        }
      })
    }
  }

  /**
   * 播放通知提示音
   */
  playNotificationSound(priority = 'normal') {
    try {
      const audio = new Audio()
      
      // 根据优先级选择不同的提示音
      switch (priority) {
        case 'high':
          audio.src = '/sounds/high-priority.mp3'
          break
        case 'urgent':
          audio.src = '/sounds/urgent.mp3'
          break
        default:
          audio.src = '/sounds/notification.mp3'
      }
      
      audio.volume = 0.5
      audio.play().catch(error => {
        console.warn('⚠️ 无法播放提示音:', error)
      })
    } catch (error) {
      console.warn('⚠️ 播放提示音失败:', error)
    }
  }

  /**
   * 标记通知为已读
   */
  async markAsRead(notificationId) {
    console.log('📖 标记通知为已读:', notificationId)
    
    // 更新本地状态
    if (this.notificationsStore) {
      this.notificationsStore.updateNotificationReadStatus(notificationId, true)
    }
    
    // 发送已读状态到服务器
    this.getWsService().then(wsService => {
      if (wsService) {
        const success = wsService.send({
          type: 'mark_read',
          payload: {
            notificationId: notificationId,
            timestamp: Date.now()
          }
        })
        
        if (!success) {
          console.warn('⚠️ 无法发送已读状态到服务器')
        }
      }
    })
  }

  /**
   * 同步已读状态
   */
  async syncReadStatus() {
    console.log('🔄 同步已读状态')
    
    if (!this.notificationsStore) {
      return
    }
    
    const unreadNotifications = this.notificationsStore.notifications.filter(n => !n.isRead)
    
    if (unreadNotifications.length > 0) {
      const notificationIds = unreadNotifications.map(n => n.id)
      
      this.getWsService().then(wsService => {
        if (wsService) {
          wsService.send({
            type: 'sync_read_status',
            payload: {
              notificationIds: notificationIds,
              timestamp: Date.now()
            }
          })
        }
      })
    }
  }

  /**
   * 处理通知点击
   */
  handleNotificationClick(notification) {
    console.log('🖱️ 通知被点击:', notification)
    
    // 根据通知类型进行不同的处理
    const { category, data } = notification
    
    switch (category) {
      case 'ticket':
        // 跳转到工单详情页
        if (data.ticketId) {
          window.location.href = `/ticket/${data.ticketId}`
        }
        break
      case 'user':
        // 跳转到用户管理页
        window.location.href = '/users'
        break
      case 'system':
        // 跳转到系统设置页
        window.location.href = '/settings'
        break
      default:
        // 跳转到通知页面
        window.location.href = '/notifications'
    }
  }

  /**
   * 触发通知点击事件
   */
  triggerNotificationClick(notification) {
    // 触发自定义事件
    const event = new CustomEvent('notification-click', {
      detail: notification
    })
    window.dispatchEvent(event)
  }

  /**
   * 启动消息处理
   */
  start() {
    console.log('🚀 启动消息处理器')
    
    // 确保已初始化
    if (!this.isInitialized) {
      console.warn('⚠️ 消息处理器未初始化，尝试重新初始化')
      this.initialize()
    }
    
    // 检查wsService是否可用
    this.getWsService().then(wsService => {
      if (wsService && typeof wsService.connect === 'function') {
        wsService.connect()
      } else {
        console.warn('⚠️ WebSocket服务不可用，无法启动连接')
      }
    })
  }

  /**
   * 停止消息处理
   */
  stop() {
    console.log('🛑 停止消息处理器')
    
    // 检查wsService是否可用
    this.getWsService().then(wsService => {
      if (wsService && typeof wsService.disconnect === 'function') {
        wsService.disconnect()
      } else {
        console.warn('⚠️ WebSocket服务不可用，无法停止连接')
      }
    })
  }

  /**
   * 获取连接状态
   */
  async getConnectionState() {
    try {
      const wsService = await this.getWsService()
      return wsService ? wsService.getConnectionState() : 'disconnected'
    } catch (error) {
      console.error('❌ 获取连接状态失败:', error)
      return 'disconnected'
    }
  }
}

// 创建全局消息处理器实例
const messageHandler = new NotificationMessageHandler()

export default messageHandler
